// npm 包
import React, { useState, useRef, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { AutoComplete, Button, message, Popconfirm, Radio, Modal } from 'antd';
import { PageContainer } from '@ant-design/pro-layout';
import { history } from 'umi';
import ProForm from '@ant-design/pro-form';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import { CopyOutlined, PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
// 自定义组件
import AddForm from './component/AddForm';
import CopyEntryModal from './component/CopyEntryModal';
import { baseUrl } from '@/utils/httpUrl';

// 数据请求
import { paperList, paperDelete, getListStatusCount } from './service';

const TableList: React.FC<{}> = () => {
  const actionRef = useRef<ActionType>();
  
  const { id } = history.location.query || {}
  const [modalVisible, setModalVisible] = useState<boolean>(false);
  const [modalType, setModalType] = useState<'copy' | 'add' | 'edit' | ''>('');
  const [statusTab, setStatusTab] = useState<string>('');
  const [statusList, setStatusList] = useState<any>();
  const [options, setOptions] = useState<{ value: string }[]>([]);
  const [testId, setTestId] = useState<number>();
  const [phoneValue, setPhoneValue] = useState<any>();
  useEffect(() => {
    let types = [{value:'',label:'全部'},{value:'notSend',label:'未发放'},{value:'sendOver',label:'已发放'}]
    setStatusList(types)
  }, []);
  
  const changeStatusTab = (e) => {
    setStatusTab(e.target.value);
    actionRef.current?.reload();
  };

  const onReload = () => {
    // const fetchStatus = async () => {
    //   const res = await getListStatusCount();
    //   setStatusList(res.result);
    // };
    // fetchStatus();
    if (actionRef.current) {
      actionRef.current.reload();
    }
  };
  const confirm = async (id: string) => {
    console.log(id)
    const result = await paperDelete({id});
    if (result.code === 200) {
      message.success('删除成功');
      onReload();
    } else {
      message.error(result.message);
    }
  };
  // const resetConfirm = async (id: string) => {
  //   const result = await resetById(id);
  //   if (result.code === 200) {
  //     message.success('删除成功');
  //     onReload();
  //   } else {
  //     message.error(result.message);
  //   }
  // };
  const columns: ProColumns[] = [
    {
      title: '试卷ID',
      dataIndex: 'id',
    },
    {
      title: '试卷名称',
      dataIndex: 'name',
      render: (_, record: any) => [
        <Link to={`/paper-list?activityId=${id}&paperId=${record.id}`}>{record.name}</Link>
      ],
    },
    {
      title: '开始时间',
      dataIndex: 'startTimeStr',
    },
    {
      title: '难度',
      dataIndex: 'level',
      valueEnum: {
        'high': '较高',
          'common': '普通',
          'low': '较低',
          'simple': '简单',
      },
    },
    {
      title: '完成奖励',
      dataIndex: 'complateAward',
    },
    {
      title: '及格奖励',
      dataIndex: 'passAward',
    },
    {
      title: '满分奖励',
      dataIndex: 'fullAward',
    },
    {
      title: '试做',
      dataIndex: 'status',
      render: (_, record: any) => [
        record.status == 'notDo' ?(
          <a
              target="_blank"
              href={baseUrl.webview + `/computation?paperId=${record.id}&isTeacher=1`}
              rel="noreferrer"
            >
              试做
            </a>
        ):(
          <a
              target="_blank"
              href={baseUrl.webview + `/computation_review?paperId=${record.id}&isTeacher=1`}
              rel="noreferrer"
            >
              查看
            </a>
        )
      ],
    },
    {
      title: '发放',
      dataIndex: 'uid',
      render: (_, record: any) => [
        record.isSend == '1' ?(
          <Link to={`/send-list?activityId=${id}&paperId=${record.id}`}>已发放</Link>
        ):(
          <Link to={`/send-list?activityId=${id}&paperId=${record.id}`}>未发放</Link>
        )
      ],
    },

    {
      title: '查看成绩',
      dataIndex: 'uid',
      render: (_, record: any) => [
        
          <Link to={`/tag-list?activityId=${id}&paperId=${record.id}`}>查看</Link>
      ],
    },
    
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          style={{ marginRight: '20px' }}
          onClick={() => {
            setModalVisible(true);
            setModalType('edit');
            setTestId(record.id)
          }}
        >
          修改
        </a>,
        <Popconfirm
          placement="top"
          title={'确定要删除试卷吗?'}
          onConfirm={() => {
            confirm(record.id);
          }}
          okText="确定"
          cancelText="取消"
        >
          <a>删除</a>
        </Popconfirm>,
      ],
    },
  ];

  

  return (
    <PageContainer 
    header={{
      title: '',
      breadcrumb: {},
    }}
    >
      <div style={{height:20}}></div>
      <ProForm.Item label="对局状态">
        <Radio.Group value={statusTab} onChange={changeStatusTab}>
          {statusList &&
            statusList.map((val: any) => (
              <Radio.Button value={val.value} style={{ marginRight: 10 }}>
                {val.label}
              </Radio.Button>
            ))}
        </Radio.Group>
      </ProForm.Item>
      <ProTable
        actionRef={actionRef}
        rowKey="id"
        request={async (params) => {
          const msg = await paperList({
            activityId: id,
            pageNo: params.current,
            pageSize: params.pageSize,
            status: statusTab,
          });
          return {
            data: msg.result.records,
            success: true,
            total: msg.result.total,
          };
        }}
        toolBarRender={() => [
          
          <Button
            type="primary"
            onClick={() => {
              setModalVisible(true);
              setModalType('copy');
            }}
          >
            <CopyOutlined /> 复制试卷
          </Button>,
          <Button
          type="primary"
          onClick={() => {
            setModalVisible(true);
            setModalType('add');
          }}
        >
          <PlusOutlined /> 创建试卷
        </Button>,
        ]}
        columns={columns}
        search={false}
      />
      <AddForm
        onCancel={() => setModalVisible(false)}
        modalVisible={modalVisible && modalType != 'copy'}
        modalType={modalType}
        testId={testId}
        onReload={onReload}
      />
      <CopyEntryModal
        onCancel={() => {
          setModalVisible(false);
        }}
        onReload={onReload}
        id={id}
        modalVisible={modalVisible && modalType === 'copy'}
        callback={() => {
          // updateCurNodeList();
          // window.location.href = `/web/app-admin/activity/activity-content/${activityId}`
        }}
      />

    </PageContainer>
  );
};

export default TableList;
